const MD5 = require('./MD5');
const app = getApp();

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

// 请求api的基础路径
const baseUrl = 'https://city.yuehuio.com';

const signKey = "AEMW14xwF2Asu6UWHtW1h0qYkT1TZB5n";//签名秘钥

// 对象按照key排序
function ksort(o) {
    let sorted = {},
        keys = Object.keys(o);
    keys.sort();
    keys.forEach((key) => {
        sorted[key] = o[key];
    })
    return sorted;
}

	// 过滤数组、对象值
function removeArrayValues(obj) {
		for (var key in obj) {
			console.log("是对象值：", obj[key] instanceof Object)
			if (Array.isArray(obj[key]) || obj[key] instanceof Object) delete obj[key]
		}
		return obj
	}

/**
 * 统一的请求封装
 * @param {String} api 请求的api地址
 * @param {JSON} params 请求携带的参数
 * @param {String} methods 请求方式，默认GET
 * @param {boolean} [loading=true] 是否显示loading，默认true
 */
function apiRequest(api, params, method = 'POST', loading = true) {
    return new Promise((resolve, reject) => {
        // 请求开始，显示loading
        // if (loading) {
        //     wx.showLoading({
        //         title: '加载中'
        //     })
        // }
        //参数添加签名秘钥
       // let sort_obj = ksort(params)
        let sort_obj = removeArrayValues(ksort(params))

        let sort_values = Object.values(sort_obj).join("&")
        console.log("sort_values:",sort_values);
        if(!!sort_values){
            params['sign'] = MD5.md5(sort_values + "&" + signKey)
        }else{
            params['sign'] = MD5.md5(signKey)
        }
        
        // 请求
        wx.request({
            url: baseUrl + api,
            data: params,
            method: method,
            dataType: 'json',
            success: function (res) {
                if (res.statusCode === 200) {
                    resolve(res) // 接收res并传到then的参数中去
                    // wx.hideLoading() // 结束加载
                } else {
                    // wx.hideLoading()
                    reject()
                }
            },
            error: function (e) {
                reject(e)
            }
        })
        wx.hideLoading()
    })
}

/**
 * htmt富文本转成文本操作
 */
function convertHtmlToText(inputText) {
    var returnText = "" + inputText;
    returnText = returnText.replace(/<\/div>/ig, '\r\n');
    returnText = returnText.replace(/<\/li>/ig, '\r\n');
    returnText = returnText.replace(/<li>/ig, ' * ');
    returnText = returnText.replace(/<\/ul>/ig, '\r\n');
    //-- remove BR tags and replace them with line break
    returnText = returnText.replace(/<br\s*[\/]?>/gi, "\r\n");

    //-- remove P and A tags but preserve what's inside of them
    returnText = returnText.replace(/<p.*?>/gi, "\r\n");
    returnText = returnText.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 ($1)");

    //-- remove all inside SCRIPT and STYLE tags
    returnText = returnText.replace(/<script.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/script>/gi, "");
    returnText = returnText.replace(/<style.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/style>/gi, "");
    //-- remove all else
    returnText = returnText.replace(/<(?:.|\s)*?>/g, "");

    //-- get rid of more than 2 multiple line breaks:
    returnText = returnText.replace(/(?:(?:\r\n|\r|\n)\s*){2,}/gim, "\r\n\r\n");

    //-- get rid of more than 2 spaces:
    returnText = returnText.replace(/ +(?= )/g, '');

    //-- get rid of html-encoded characters:
    returnText = returnText.replace(/&nbsp;/gi, " ");
    returnText = returnText.replace(/&amp;/gi, "&");
    returnText = returnText.replace(/&quot;/gi, '"');
    returnText = returnText.replace(/&lt;/gi, '<');
    returnText = returnText.replace(/&gt;/gi, '>');
    returnText = returnText.replace("&ldquo;", "'");
    returnText = returnText.replace("&rdquo;", "'");
    return returnText;
}

function isCard(e) {
    var code = e
    //身份证号合法性验证 
    //支持15位和18位身份证号
    //支持地址编码、出生日期、校验位验证
    var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
    var tip = "";
    var pass = true;
    var reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/;
    if (!code || !code.match(reg)) {
        tip = "身份证号格式错误";
        pass = false;
    } else if (!city[code.substr(0, 2)]) {
        tip = "地址编码错误";
        pass = false;
    } else {
        //18位身份证需要验证最后一位校验位
        if (code.length == 18) {
            code = code.split('');
            //∑(ai×Wi)(mod 11)
            //加权因子
            var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
            //校验位
            var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
            var sum = 0;
            var ai = 0;
            var wi = 0;
            for (var i = 0; i < 17; i++) {
                ai = code[i];
                wi = factor[i];
                sum += ai * wi;
            }
            var last = parity[sum % 11];
            if (parity[sum % 11] != code[17]) {
                tip = "校验位错误";
                pass = false;
            }
        }
    }
    var returnParam = {
        'errorMess': tip,
        'isPass': pass
    }
    return returnParam;
}

module.exports = {
    formatTime: formatTime,
    apiRequest: apiRequest,
    isCard: isCard,
    convertHtmlToText: convertHtmlToText
}
